package com.cavy.platform.server.service;

import com.cavy.platform.server.domain.job.JobAction;
import com.cavy.platform.server.dto.JobLogDto;
import com.cavy.platform.server.dto.JobSearchListDto;
import com.cavy.platform.server.dto.LogItemDto;
import com.cavy.platform.server.repository.JobLogRepository;
import com.cavy.platform.server.repository.JobRepository;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Service
public class JobService {
    @Autowired
    private JobRepository repository;
    @Autowired
    private JobLogRepository logRepository;

    private ObjectMapper mapper = new ObjectMapper();

    public JobService() {
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    public List<JobAction> list(JobSearchListDto dto) {
        return repository.find(dto);
    }

    public JobAction info(String workSpace, String project, String pipeline, String number) {
        return repository.load(workSpace, project, pipeline, number);
    }

    //1,获取文件
    //2,读取文件
    //3,转换文件
    public void getLog(HttpServletResponse response, JobLogDto dto) throws IOException {
        File file = logRepository.load(dto);
        if (file == null) {
            return;
        }
        try (BufferedReader reader = new BufferedReader(new FileReader(file));
             BufferedWriter writer = new BufferedWriter(response.getWriter());) {
            String line = reader.readLine();
            writer.write("[");
            while (line != null) {
                writer.write(convert(line));
                line = reader.readLine();
                if (line != null) {
                    writer.write(",");
                }
            }
            writer.write("]");
            writer.flush();
        }
    }

    public String convert(String line) {
        String[] split = line.split("\t");
        try {
            LogItemDto value = mapper.readValue(split[1], LogItemDto.class);
            value.setTime(split[0]);
            return mapper.writeValueAsString(value);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
